<template>
	<view>
		<u-navbar title="添加好友">
		</u-navbar>
		<u-sticky>
			<!-- 只能有一个根元素 -->
			<view class="u-p-x-30 u-p-y-10 bg-white">
				<u-search :focus="true" v-model="key" placeholder="搜索用户号/手机号" :showAction="false"></u-search>
			</view>
		</u-sticky>
		<view class="u-m-t-20">
			<navigator :url="`/pages/user/info?id=${item.userId}`" hover-class="none" v-for="(item,index) in users.list" :key="index" class="u-flex bg-white u-p-x-30 u-p-y-14 u-border-bottom">
				<u-avatar :src="item.avatarUrl" mode="square"></u-avatar>
				<view class="u-m-l-12 u-flex-1 u-font-30">
					<text v-for="(sub,j) in item.txtArr" :key="j" :class="{'text-blue':sub.l}">{{sub.t}}</text>
				</view>
				<view v-show="userInfo.userId!=item.userId" @tap.stop>
					<u-button size="mini" :plain="true" type="primary" @click="apply(item)">添加</u-button>
				</view>
			</navigator>
			<view class="u-text-center u-p-y-20" v-show="key&&users.nomore">
				<text class="text-gray" v-if="users.list.length">没有更多了</text>
				<text class="text-gray" v-else>没找到您需要的用户</text>
			</view>
		</view>
		<u-modal 
			v-model="ask.show"
			title="添加好友" 
			confirm-text="申请"
			showCancelButton
			@cancel="reject"
			@confirm="resolve"
		>
			<view class="u-p-y-20 u-p-x-30">
				<textarea v-model="ask.content" class="textarea" maxlength="30" placeholder="申请理由(30字内)" />
			</view>
		</u-modal>
		<vip-dialog v-model="vipAsk.show">
			<text v-if="vipAsk.content" slot="label">{{vipAsk.content}}</text>
		</vip-dialog>
	</view>
</template>

<script>
	import {get as getStorage,set as setStorage} from "@/utils/storage.js"
	import {toast,delay} from "@/utils/util.js"
	import {searchUsers} from "@/api/user.js"
	import {applyFriend} from "@/api/addr.js"
	import {mapGetters,mapActions} from "vuex"
	import vipDialog from "@/components/dialogs/vip/index.vue"
	import chat, { dictateTypes, msgTypes } from "@/IM"
	import { ConversationType } from "@/entity/ConversationType"
	const last_apply = 'apply_friend_last'
	export default {
		components:{
			vipDialog,
		},
		data() {
			return {
				key:'', 
				users:{
					list:[],
					pageNo:1,
					pageSize:10,
					loading:false,
					nomore:false
				},
				ask:{
					show:false,
					content:''
				},
				vipAsk:{
					show:false,
					content:'',
				},
				bridge:null
			};
		},
		computed:{
			...mapGetters('user',['userInfo'])
		},
		watch:{
			key(val){
				this.$u.debounce(this.resetUsers, 500)
			}
		},
		onReachBottom(){
			this.moreUsers()
		},
		methods:{
			...mapActions('addr',['loadOneFriend']),
			...mapActions('chat', ['sendMessage','saveHistory','setConversation']),
			async apply(user){
				
				
				
				
				
				
				
				await new Promise((resolve,reject)=>{
					this.bridge={
						resolve,
						reject
					}
					this.ask.show = true
					this.ask.content = `我是${this.userInfo.userName}`
				})
				
				const {friendId} = await applyFriend({
					uid:user.userId,
					remark:this.ask.content
				})
				if(friendId){
					toast('好友添加成功')
					this.loadOneFriend(user.userId)
					chat.dictate({
						to:user.userId,
						msgType:dictateTypes.addFriend,
						content:'添加好友成功',
						extras:{}
					})
					const msg = chat.createMessage({
						to: user.userId,
						content: '我们已经是好友了，现在开始聊天吧',
						msgType: msgTypes.TEXT
					})
					this.setConversation({
						id:user.userId,
						avatar:user.avatarUrl,
						name:user.userName,
						type:ConversationType.Single,
						lastMessage:msg
					})
					msg.readBody = {readCount:0,unreadCount:1}
					msg.status = 'loading';
					try {
						await this.sendMessage({
							message: msg,
							id:user.userId
						})
						await chat.send(msg)
						msg.status = 'success';
						this.saveHistory()
					} catch (e) {
						msg.status = 'error';
					}
				}else{
					await delay(200)
					toast('好友申请成功')
				}
			},
			
			resolve(e){
				this.bridge&&this.bridge.resolve&&this.bridge.resolve(e)
			},
			reject(e){
				this.bridge&&this.bridge.reject&&this.bridge.reject(e)
			},
			lightTxt(txt,key){
				const arr = txt.split(key)
				const txtArr = []
				for (var i = 0; i < arr.length-1; i++) {
					txtArr.push({
						t:arr[i],
						l:false
					},{
						t:key,
						l:true
					})
				}
				txtArr.push({
					t:arr.slice(-1)[0],
					l:false
				})
				return txtArr
			},
			async resetUsers(){
				this.users.nomore = false
				this.users.list = []
				this.users.pageNo = 1
				await this.moreUsers()
			},
			async moreUsers(){
				const list = await this.getUsers();
				this.users.list.push(...list)
			},
			async getUsers(){
				if(this.users.loading){
					throw new Error('正在请求中')
				}
				try{
					if(this.users.nomore||!this.key){
						return[]
					}
					this.users.loading = true
					const list = await searchUsers({key:this.key,...this.users})
					if(!list||list.length<this.users.pageSize){
						this.users.nomore = true
					}else{
						this.users.pageNo++
					}
					return list.map(item=>({...item,txtArr:this.lightTxt(item.userName,this.key)}))
				}finally{
					this.users.loading = false
				}
			}
		}
	}
</script>
<style>
	page{
		background-color: #F5F5F5;
	}
</style>
<style lang="scss" scoped>
	.textarea{
		width: 100%;
		height: 160rpx;
		background-color: #F5F5F5;
		padding: 20rpx;
		border-radius: 10rpx;
		font-size: 28rpx;
	}
</style>
